package com.yqya.springboot.email.server.service.impl;

import java.util.Date;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.yqya.springboot.email.server.dto.EmailDTO;
import com.yqya.springboot.email.server.service.EmailService;
import com.yqya.springboot.email.server.vo.EmailVO;

/**
 * 邮件 服务实现类
 *
 * @author Kevin
 * @date 2019-06-30
 */
@Service
public class EmailServiceImpl implements EmailService {

    private static final Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);

    @Resource
    private JavaMailSenderImpl mailSender;

    @Override
    public EmailVO sendEmail(EmailDTO dto) {
        EmailVO vo = new EmailVO();
        try {
            // 1.检测邮件
            checkEmail(dto);

            // 2.发送邮件
            sendMineEmail(dto);

            // 3.保存邮件
            vo = saveEmail(dto);
            vo.setStatus("success");
            return vo;
        } catch (Exception e) {
            logger.error("++++++ 发送邮件失败!", e);
            BeanUtils.copyProperties(dto, vo);
            vo.setStatus("fail");
            vo.setError("发送邮件失败");
        }

        return vo;
    }

    /**
     * 检测邮件信息
     *
     * @param dto
     */
    private void checkEmail(EmailDTO dto) {
        if (StringUtils.isEmpty(dto.getTo())) {
            throw new RuntimeException("收信人地址不能为空");
        }

        if (StringUtils.isEmpty(dto.getSubject())) {
            throw new RuntimeException("邮件主题不能为空");
        }

        if (StringUtils.isEmpty(dto.getText())) {
            throw new RuntimeException("邮件内容不能为空");
        }
    }

    /**
     * 发送复杂邮件
     *
     * @param dto
     */
    private void sendMineEmail(EmailDTO dto) {
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true);
            String from = getEmailSendFrom();
            messageHelper.setFrom(from);
            messageHelper.setTo(dto.getTo().split(","));
            messageHelper.setSubject(dto.getSubject());
            messageHelper.setText(dto.getText());

            // 抄送
            String cc = dto.getCc();
            if (!StringUtils.isEmpty(cc)) {
                messageHelper.setCc(cc.split(","));
            }

            // 密送
            String bcc = dto.getBcc();
            if (!StringUtils.isEmpty(bcc)) {
                messageHelper.setBcc(bcc.split(","));
            }

            // 附件
            MultipartFile[] multipartFiles = dto.getMultipartFiles();
            if (multipartFiles != null) {
                for (MultipartFile multipartFile : multipartFiles) {
                    messageHelper.addAttachment(multipartFile.getOriginalFilename(), multipartFile);
                }
            }

            messageHelper.setSentDate(new Date());

            // 正式发送邮件
            // todo 待优化（放到队列中）
            mailSender.send(messageHelper.getMimeMessage());
            logger.info("发送邮件成功： {} -> {}", from, dto.getTo());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 保存邮件
     *
     * @param dto
     * @return
     */
    private EmailVO saveEmail(EmailDTO dto) {
        // todo 将邮件信息保存到数据
        EmailVO vo = new EmailVO();
        BeanUtils.copyProperties(dto, vo);
        return vo;
    }

    /**
     * 获取邮件作者
     */
    @Override
    public String getEmailSendFrom() {
        return mailSender.getJavaMailProperties().getProperty("from");
    }

}
